﻿using blackhouse.JavaScript.JQuery;
using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Business.Groups;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace blackhouse.WebNemo.Web.Controls.ReferenceGallery {
    public class EditReferenceGallery : EditRecordValue {

        #region Fields

        private Panel holder;
        private Panel uploadHolder;
        private FileUpload upload;
        private Label uploadLabel;
        private HiddenField field;

        private IGroup mainGroup;
        private IGroup refGroup;
        private Factory factory = Factory.Instance();
        private GalleryController controller;
        private GalleryItem[] galleryItems;
        private bool multiPhotosEditor;

        #endregion

        #region Properties

        public override bool DisplayInline {
            get { return false; }
        }

        #endregion

        #region Methods

        protected override void PopulateControl() {
            this.SetInstance();
            this.EnsureChildControls();
            this.holder.Attributes.Add("data-group", this.mainGroup.Id.ToString());
            this.holder.Attributes.Add("data-refgroup", this.refGroup.Id.ToString());
            this.holder.Attributes.Add("data-column", this.column.ColumnId.ToString());
            this.AddJavaScript();
            this.BuildPhotoList();
            this.field.Value = String.Join(",", this.galleryItems.Select(gi => gi.RecordId.ToString()).ToArray());
        }

        public override void SaveInRecord() {
            if (this.multiPhotosEditor)
                this.SaveInRecordMultiEditor();
            else
                this.SaveInRecordOnePhoto();
        }

        public void SaveInRecordMultiEditor() {
            List<int> selectedRefs = new List<int>();
            string rSelected = Page.Request[this.field.UniqueID];
            if (!String.IsNullOrEmpty(rSelected)) {
                string[] rSelecteds = rSelected.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                for (int xs = 0; xs < rSelecteds.Length; xs++) {
                    int selected;
                    if (Int32.TryParse(rSelecteds[xs], out selected))
                        selectedRefs.Add(selected);
                }
            }
            this.record.SetRecords(this.column.ColumnName, selectedRefs.ToArray());
        }

        public void SaveInRecordOnePhoto() {
            int selectedRef = 0;
            string rSelected = Page.Request[this.field.UniqueID];
            if (!String.IsNullOrEmpty(rSelected)) {
                if (!Int32.TryParse(rSelected, out selectedRef))
                    selectedRef = 0;
            }
            this.record.SetRecord(this.column.ColumnName, selectedRef);
        }

        protected override void CreateChildControls() {
            base.CreateChildControls();

            this.holder = new Panel();
            this.Controls.Add(this.holder);
            this.holder.CssClass = "gallery-wrapper";

            this.uploadHolder = new Panel();
            this.Controls.Add(this.uploadHolder);
            this.uploadHolder.CssClass = "upload-holder record-edit-idi";

            this.uploadLabel = new Label();
            this.uploadHolder.Controls.Add(this.uploadLabel);
            this.uploadLabel.Text = (this.multiPhotosEditor) ? "Dodaj nowe zdjęcie:" : "Wstaw zdjęcie:";
            this.uploadLabel.CssClass = "title";

            this.upload = new FileUpload();
            this.uploadHolder.Controls.Add(this.upload);

            this.field = new HiddenField();
            this.Controls.Add(this.field);
        }

        private void SetInstance() {
            this.mainGroup = this.record.GetGroup();
            this.refGroup = this.factory.GetGroup(this.column.RelatedGroupId);
            this.controller = new GalleryController(this.record, this.mainGroup, this.refGroup, this.column);
            this.galleryItems = this.controller.GetGalleryPhotos(new Size(250, 220));
            this.multiPhotosEditor = this.column.ColumnType == FieldType.ManyReference;
        }

        private void AddJavaScript()
        {
            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeJQueryAjaxFileUpload();
#if DEBUG
            jql.IncludeFileBasedOnJQuery("blackhouse.WebNemo.Web.Scripts.reference-gallery.js,blackhouse.WebNemo.Web");
#else
            jql.IncludeFileBasedOnJQuery("blackhouse.WebNemo.Web.Scripts.reference-gallery.min.js,blackhouse.WebNemo.Web");
#endif
        }

        private void BuildPhotoList() {
            StringBuilder buildRepeatedPhotosWrap = new StringBuilder();
            buildRepeatedPhotosWrap.AppendFormat("<div class=\"photos\" data-reftype=\"{0}\">", this.multiPhotosEditor ? "many" : "one");
            if (this.galleryItems.Length > 0) {
                foreach (GalleryItem item in this.galleryItems)
                    this.BuildPhotoListItem(buildRepeatedPhotosWrap, item);
            }
            else
                this.BuildPhotoListItem(buildRepeatedPhotosWrap, new GalleryItem());

            buildRepeatedPhotosWrap.Append("</div>");
            Literal l = new Literal();
            this.holder.Controls.Add(l);
            l.Text = buildRepeatedPhotosWrap.ToString();
        }

        private void BuildPhotoListItem(StringBuilder buildRepeatedPhotosWrap, GalleryItem item) {
            buildRepeatedPhotosWrap.Append("<div class=\"item\" style=\"width:250px;height:250px");
            if (item.RecordId > 0)
                buildRepeatedPhotosWrap.AppendFormat("\" data-id=\"{0}\">", item.RecordId);
            else
                buildRepeatedPhotosWrap.Append(";display:none\">");
            buildRepeatedPhotosWrap.AppendFormat("<img src=\"{0}\" alt=\"{1}\" />", item.PhotoSrc, item.PhotoName);
            buildRepeatedPhotosWrap.Append("<a>Usuń zdjęcie</a>");
            buildRepeatedPhotosWrap.Append("</div>");
        }

        #endregion

    }
}